package fragments;


import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseFragment;
import com.example.administrator.newxlmedical.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import beans.GoodsStatisticsBean;
import beans.OperateGoodsDetailsBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import constants.Constants;
import utils.ActivityUtil;
import utils.CustomSharedPreferencePath;

public class CopyLogFragment extends BaseFragment {


    @BindView(R.id.lv)
    TextView tv;
    @BindView(R.id.serialport)
    EditText et_serialport;
    @BindView(R.id.bt)
    Button bt_serialport;
    @BindView(R.id.inventort)
    EditText et_inventory;
    @BindView(R.id.bt_up)
    Button bt_inventory;
    Unbinder unbinder;
    Button btCount;
    @BindView(R.id.bt_agin)
    Button btAgin;
    @BindView(R.id.bt_delete)
    Button btDelete;
    private StringBuilder sb;
    private GoodsStatisticsBean bean;
    private List<GoodsStatisticsBean.DataBean> list;
    private SharedPreferences sharedPreferences;
    private FileOutputStream outputStream;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View inflate = inflater.inflate(R.layout.fragment_copy_log, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        sharedPreferences = ActivityUtil.getSharedPreferences(mContext);

        sb = new StringBuilder();
        try {
            if (Constants.IS_FUYI) {
                sb.append("/mnt");
                getUsbPath2Fuyi();
            } else {
                sb.append("/mnt/usb_storage");
                getUsbPath2Xiehe();
            }
            Log.e("TTT", "onCreate: " + sb.toString());

        } catch (Exception e) {
            e.printStackTrace();

            tv.setText("获取U盘路径失败");
        }

        bt_serialport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String fileName = et_serialport.getText().toString();
                try {

                    int sum = 0;
                    int read = 0;

                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/serialport/" + fileName);
                    long length = file.length();

                    if (file.exists()) {
                        FileInputStream source = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/serialport/" + fileName);
                        FileOutputStream fs = new FileOutputStream(sb.toString() + "/" + fileName);

                        byte[] bytes = new byte[2048];

                        while ((read = source.read(bytes)) != -1) {
                            sum += read;
                            fs.write(bytes, 0, read);
                            long l = sum % length;
                            if (l == 0) {
                                tv.setText("已完成");
                            } else {
                                tv.setText(l + "%");
                            }
                        }

                        source.close();
                        fs.close();
// 2018-9-19.log
                    } else {
                        tv.setText("文件不存在!");
                    }

                } catch (Exception e) {

                    tv.setText("复制文件出错!");

                }

            }
        });

        bt_inventory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String fileName = et_inventory.getText().toString();
                try {

                    int sum = 0;
                    int read = 0;

                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/InventoryError/" + fileName);
                    long length = file.length();

                    if (file.exists()) {
                        FileInputStream source = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/InventoryError/" + fileName);
                        FileOutputStream fs = new FileOutputStream(sb.toString() + "/" + fileName);

                        byte[] bytes = new byte[2048];

                        while ((read = source.read(bytes)) != -1) {
                            sum += read;
                            fs.write(bytes, 0, read);
                            long l = sum % length;
                            if (l == 0) {
                                tv.setText("已完成");
                            } else {
                                tv.setText(l + "%");
                            }
                        }

                        source.close();
                        fs.close();
// 2018-9-19.log
                    } else {
                        tv.setText("文件不存在!");
                    }

                } catch (Exception e) {

                    tv.setText("复制文件出错!");

                }

            }

        });

        btDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, OperateGoodsDetailsBean.DataBean> errorMap = new HashMap<>();
                CustomSharedPreferencePath.saveData(mContext, Constants.RECORD_ERROR_GOODS, errorMap);
            }
        });

        return inflate;
    }

    private void getUsbPath2Xiehe() {
        File os = new File(sb.toString());
        if (os.exists()) {
            File[] files = os.listFiles();
            int count = 0;
            for (File file : files) {
                Log.e("TTT", "onCreate: " + file.getName() + "    " + file.listFiles().length);
                File[] f = file.listFiles();
                if (f.length > 0) {
                    count++;
                    sb.append("/" + file.getName());
                    File subFile = f[0];
                    sb.append("/" + subFile.getName());
                }
            }
            if (count != 0) {
                tv.setText("已获取U盘路径");
            } else {
                tv.setText("获取U盘路径失败");
            }
        } else {
            tv.setText("获取U盘路径失败");
        }
    }

    private void getUsbPath2Fuyi() {
        File os = new File(sb.toString());
        if (os.exists()) {
            File[] files = os.listFiles();
            int count = 0;
            for (File file : files) {
                if (file != null && file.getName().startsWith("usbhost")) {
                    File[] f = file.listFiles();
                    if (f != null && file.listFiles().length > 0) {
                        count++;
                        sb.append("/" + file.getName());
                        break;
                    }
                }
            }
            if (count != 0) {
                tv.setText("已获取U盘路径");
            } else {
                tv.setText("获取U盘路径失败");
            }
        } else {
            tv.setText("获取U盘路径失败");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.bt_agin})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.bt_agin:
                sb = new StringBuilder();
                tv.setText("");
                try {
                    if (Constants.IS_FUYI) {
                        sb.append("/mnt");
                        getUsbPath2Fuyi();
                    } else {
                        sb.append("/mnt/usb_storage");
                        getUsbPath2Xiehe();
                    }
                    Log.e("TTT", "onCreate: " + sb.toString());

                } catch (Exception e) {
                    e.printStackTrace();

                    tv.setText("获取U盘路径失败");
                }

                break;
        }
    }

}
